package com.erge.student.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erge.common.utils.DateUtils;
import com.erge.common.utils.SecurityUtils;
import com.erge.student.domain.ClassDO;
import com.erge.student.domain.vo.GenderPresentVO;
import com.erge.student.domain.vo.ReportChartVO;
import com.erge.student.domain.vo.StudentCountChartVO;
import com.erge.student.mapper.ClassMapper;
import com.erge.student.service.IClassService;
import org.springframework.stereotype.Service;
import com.erge.student.mapper.StudentMapper;
import com.erge.student.domain.StudentDO;
import com.erge.student.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.util.CollectionUtils;

/**
 * 学生Service业务层处理
 *
 * @author roydon
 * @date 2025-05-22
 */
@RequiredArgsConstructor
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, StudentDO> implements IStudentService {
    private final StudentMapper studentMapper;
    private final ClassMapper classMapper;
    private final IClassService classService;

    /**
     * 查询学生
     *
     * @param id 学生主键
     * @return 学生
     */
    @Override
    public StudentDO selectStudentById(Long id) {
        return studentMapper.selectStudentById(id);
    }

    /**
     * 查询学生列表
     *
     * @param student 学生
     * @return 学生
     */
    @Override
    public List<StudentDO> selectStudentList(StudentDO student) {
        return studentMapper.selectStudentList(student);
    }

    /**
     * 新增学生
     *
     * @param student 学生
     * @return 结果
     */
    @Override
    public int insertStudent(StudentDO student) {
        student.setCreateBy(SecurityUtils.getUsername());
        student.setCreateTime(DateUtils.getNowDate());
        return studentMapper.insertStudent(student);
    }

    /**
     * 修改学生
     *
     * @param student 学生
     * @return 结果
     */
    @Override
    public int updateStudent(StudentDO student) {
        student.setUpdateBy(SecurityUtils.getUsername());
        student.setUpdateTime(DateUtils.getNowDate());
        return studentMapper.updateStudent(student);
    }

    /**
     * 批量删除学生
     *
     * @param ids 需要删除的学生主键
     * @return 结果
     */
    @Override
    public int deleteStudentByIds(Long[] ids) {
        return studentMapper.deleteStudentByIds(ids);
    }

    /**
     * 删除学生信息
     *
     * @param id 学生主键
     * @return 结果
     */
    @Override
    public int deleteStudentById(Long id) {
        return studentMapper.deleteStudentById(id);
    }

    @Override
    public StudentCountChartVO countChart() {
        List<StudentDO> studentList = this.list();
        // 统计数据
        if (CollectionUtils.isEmpty(studentList)) {
            return new StudentCountChartVO(0, 0, 0, 0, 0, 0);
        }
        int totalCount = studentList.size();
        int reportCount = studentList.stream().filter(student -> student.getReportStatus().equals("1")).toArray().length;
        int reportManCount = studentList.stream().filter(student -> student.getReportStatus().equals("1") && student.getGender().equals("0")).toArray().length;
        int reportWomanCount = studentList.stream().filter(student -> student.getReportStatus().equals("1") && student.getGender().equals("1")).toArray().length;
        int payCount = studentList.stream().filter(student -> student.getTuitionStatus().equals("1")).toArray().length;
        int dormCount = studentList.stream().filter(student -> student.getDormBuilding() != null && !student.getDormBuilding().trim().isEmpty()).toArray().length;
        return StudentCountChartVO.builder()
                .totalCount(totalCount)
                .reportCount(reportCount)
                .reportManCount(reportManCount)
                .reportWomanCount(reportWomanCount)
                .payCount(payCount)
                .dormCount(dormCount)
                .build();
    }

    /**
     * 院系报道情况
     */
    @Override
    public List<ReportChartVO> reportChart() {
        // 查找顶级id
        LambdaQueryWrapper<ClassDO> cqw = new LambdaQueryWrapper<>();
        cqw.eq(ClassDO::getParentId, 0);
        List<ClassDO> pClassList = classService.list(cqw);
        if (CollectionUtils.isEmpty(pClassList)) {
            return null;
        }
        // 查询二级学院
        List<ClassDO> classSList = new ArrayList<>();
        for (ClassDO pClass : pClassList) {
            LambdaQueryWrapper<ClassDO> cqw2 = new LambdaQueryWrapper<>();
            cqw2.eq(ClassDO::getParentId, pClass.getId());
            List<ClassDO> classList = classService.list(cqw2);
            if (CollectionUtils.isEmpty(classList)) {
                continue;
            }
            classSList.addAll(classList);
        }
        // 统计学院报道人数
        if(CollectionUtils.isEmpty(classSList)){
            return null;
        }
        List<ReportChartVO> reportChartVOList = new ArrayList<>();
        for (ClassDO classS : classSList) {
            LambdaQueryWrapper<StudentDO> sqw = new LambdaQueryWrapper<>();
            sqw.eq(StudentDO::getFaculty, classS.getClassName());
            sqw.eq(StudentDO::getReportStatus, "1");
            long count = this.count(sqw);
            reportChartVOList.add(ReportChartVO.builder()
                    .collegeName(classS.getClassName())
                    .count(count)
                    .build());
        }
        return reportChartVOList;
    }

    @Override
    public GenderPresentVO genderChart() {
        // 计算男女生所占比例
        List<StudentDO> studentList = this.list();
        if (!CollectionUtils.isEmpty(studentList)) {
            long manCount = studentList.stream().filter(student -> student.getGender().equals("0")).toArray().length;
            // 获取男生，保留两位小数
            String manP = String.format("%.2f", (double) manCount / studentList.size() * 100);

            long womanCount = studentList.stream().filter(student -> student.getGender().equals("1")).toArray().length;
            String womanP = String.format("%.2f", (double) womanCount / studentList.size() * 100);
            return GenderPresentVO.builder()
                    .man(manP)
                    .woman(womanP)
                    .build();
        }
        return GenderPresentVO.builder()
                .man(String.valueOf(0))
                .woman(String.valueOf(0))
                .build();
    }
}
